<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								入库单
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" ref="vFormRef" :rules="rules" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col
								:span="!formData.receiptTypeId?24:formData.receiptTypeId===177?24:formData.receiptTypeId===180?24:12">
								<el-form-item label="入库单号" prop="receiptNumber" class="form-item-bg">
									<el-input type="text" v-model="formData.receiptNumber" placeholder="自动生成无需填写"
										readonly clearable></el-input>
								</el-form-item>
							</el-col>
							<!-- 采购订单 -->
							<el-col :span="formData.receiptTypeId===178?12:0">
								<el-form-item label="采购订单" prop="purchaseOrder" class="form-item-bg">
									<el-select @clear="selectClear('purchaseOrder')" v-model="formData.purchaseOrder"
										@change="(value:any)=>selectChange(value,'purchaseOrder')" multiple
										ref="purchaseOrder" clearable>
										<el-option v-for="item in purchaseOrderOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon
															:color="purchaseOrderOption[purchaseOrderIndex]?.color">
															<component
																:is="purchaseOrderOption[purchaseOrderIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{purchaseOrderOption[purchaseOrderIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<!-- 退货订单 -->
							<el-col :span="formData.receiptTypeId===179?12:0">
								<el-form-item label="销售退货订单" prop="return" class="form-item-bg">
									<el-select @clear="selectClear('return')" v-model="formData.return"
										@change="(value:any)=>selectChange(value,'returns')" multiple ref="returns"
										clearable>
										<el-option v-for="item in returnOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="returnOption[returnIndex]?.color">
															<component :is="returnOption[returnIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{returnOption[returnIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<!--  -->
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="入库状态" prop="entryStatusId" class="form-item-bg">
									<el-input readonly type="text" clearable>
										<template #prefix>
											<div>
												<el-check-tag
													:style="`color: ${entryStatusIndex===key?'#fff':''};${entryStatusIndex===key?`background: ${item.bg}`:''}`"
													v-for="(item,key) in entryStatusTags" :key="key"
													:checked="entryStatusIndex===key"
													@change="tagChange(key,'entryStatusId')">{{item.text}}</el-check-tag>
											</div>
										</template>
									</el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="入库类型" prop="receiptType" class="form-item-bg">
									<el-select @clear="selectClear('receiptType')" v-model="formData.receiptType"
										@change="(value:any)=>selectChange(value,'receiptType')" multiple
										ref="receiptType" clearable>
										<el-option v-for="(item, key) in receiptTypeOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<el-tag style="border: 0;" :color="item?.color" round effect="dark">
												{{ item?.label }}
											</el-tag>
											<!--  -->
										</el-option>
										<!--  -->
										<template #tag>
											<el-tag style="border: 0;" v-if="receiptTypeOption[receiptTypeIndex]?.value"
												:color="receiptTypeOption[receiptTypeIndex]?.color" round effect="dark">
												{{ receiptTypeOption[receiptTypeIndex]?.label }}
											</el-tag>
										</template>
									</el-select>
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>入库信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="申请人" prop="requester">
									<el-input type="text" v-model="formData.requester" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="申请日期" prop="requestDate">
									<el-date-picker v-model="formData.requestDate" style="width:100%;" type="date" />
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<!--  -->
						<el-form-item label="入库总量" prop="totalQuantity">
							<el-input type="text" readonly v-model="formData.totalQuantity" placeholder="自动计算结果"
								clearable></el-input>
						</el-form-item>
						<!--  -->
						<div class="static-content-item">
							<div>入库审核</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<!--  -->
								<el-form-item label="审批人" prop="approver" class="form-item-bg1">
									<el-input type="text" v-model="formData.approver" clearable></el-input>
								</el-form-item>
								<!--  -->
							</el-col>
							<el-col :span="12">
								<!--  -->
								<el-form-item label="入库日期" prop="receiptDate" class="form-item-bg1">
									<el-date-picker v-model="formData.receiptDate" style="width:100%;" type="date" />
								</el-form-item>
								<!--  -->
							</el-col>
						</el-row>
						<!--  -->
						<el-form-item label="入库拍照" prop="receiptPhoto">
							<el-input class="my" readonly type="text" clearable>
								<template #prefix>
									<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
										:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
										:limit="1">
										<el-button v-if="!formData.receiptPhoto" text :icon="UploadFilled">
											上传图片
										</el-button>
										<el-image v-else preview-teleported
											style="width: 30px; height: 30px;margin: 10px auto;"
											:src="formData.receiptPhoto" :preview-src-list="[formData.receiptPhoto]" />
									</el-upload>
								</template>
							</el-input>
						</el-form-item>
						<!--  -->
						<el-form-item label="备注" prop="remark">
							<el-input type="text" v-model="formData.remark" clearable></el-input>
						</el-form-item>
						<!--  -->

						<el-form-item>
							<el-input type="text" ref="salesPerson" readonly clearable class="my1">
								<template #prefix>
									<div style="margin: 0;padding: 0;">
										<el-tabs v-model="activeName" @tab-click="handleClick" class="my">
											<el-tab-pane label="入库明细" name="order">
												<div class="flex-space-between"
													style="height: 48px;padding-left: 10px;">
													<el-text type="info" size="small">
														来自 <el-text type="primary" size="small">入库明细</el-text> 的数据
														共{{formData.tableData.length}}条
													</el-text>
													<el-text>
														<el-tooltip effect="light" :hide-after="50" content="创建"
															placement="top">
															<div class="my-a" @click="setTableData">
																<el-icon size="16px" color="#409EFF">
																	<CirclePlus />
																</el-icon>
															</div>
														</el-tooltip>
													</el-text>
												</div>
												<!--  -->
												<el-scrollbar style="width: calc(100vw - 48px - 32px);height: 300px;">
													<el-table @cell-dblclick="tableCellClick" v-loading="loading"
														:data="formData.tableData" :stripe="false" table-layout="auto"
														:default-sort="{}" border style="width: 100%;height: 300px;"
														class="my">
														<el-table-column width="76" fixed="left" prop="id"
															:sortable="false">
															<template #default="scope">
																<el-tooltip effect="light" :hide-after="50" content="复制"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="copyTableData(scope.$index)"
																		:icon="DocumentAdd"></el-button>
																</el-tooltip>
																<el-tooltip effect="light" :hide-after="50" content="删除"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="deleteTableData(scope.$index)"
																		:icon="Delete"></el-button>
																</el-tooltip>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="productId" label="入库产品*(可选)"
															:sortable="false">
															<template #default="scope">
																<el-form-item v-if="!scope.row.productId" class="my"
																	:prop="`tableData[${scope.$index}].productId`"
																	:rules="[{required: true,message: '入库产品必选',trigger: 'change'}]">
																	<el-input type="number" class="my-s"
																		v-model="scope.row.productId" clearable
																		readonly></el-input>
																</el-form-item>
																<el-text v-else>
																	<div class="flex-align-center"
																		v-if="scope.row?.products">
																		<el-icon :color="scope.row?.products.color">
																			<component :is="scope.row?.products.icon">
																			</component>
																		</el-icon>
																		<el-text size="small" style="margin-left: 6px;">
																			{{scope.row?.products.label}}
																		</el-text>
																	</div>
																</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="unitId" label="单位"
															:sortable="false">
														</el-table-column>
														<el-table-column width="140" prop="inboundQuantity"
															label="入库数量*(可选)" :sortable="false">
															<template #default="scope">
																<el-form-item v-if="!scope.row.inboundQuantity"
																	class="my"
																	:prop="`tableData[${scope.$index}].inboundQuantity`"
																	:rules="[{required: true,message: '入库数量必填',trigger: 'change'}]">
																	<el-input type="number" class="my-s"
																		v-model="scope.row.inboundQuantity" clearable
																		readonly></el-input>
																</el-form-item>
																<el-text v-else>{{scope.row.inboundQuantity}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="notes" label="备注*(可选)"
															:sortable="false">
														</el-table-column>
													</el-table>
												</el-scrollbar>
											</el-tab-pane>
										</el-tabs>
									</div>
								</template>
							</el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
			<!--  -->
			<levitation ref="levitationRef" :option="selectCell.option" :types="types" :st_type="selectCell.type"
				:params="levitationParams" :observerElement="scrollbarRef" :element="element" @change="levitationChange"
				@blur="levitationBlur" />
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { Grid, UserFilled, GoodsFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, UploadFilled, Van } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber, findIndexByLabel } from '../../../utils';
	import { formatDate } from '../../../utils/date';
	import { useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { getShipments } from '../../../api/shipmentAPI';
	import { ElMessage, FormInstance } from 'element-plus';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	const activeName = ref('order');
	//levitation start
	const element = ref(null);
	const levitationRef = ref(null);
	const scrollbarRef = ref(null);
	const types = ref('');
	const selectCell = ref({
		id: 0,
		property: '',
		type: '',
		option: []
	});
	const levitationParams = ref(null);
	//levitation end

	// 表单
	const formData = ref({
		receiptNumber: null,//入库单号
		entryStatusId: null,//入库状态
		entryStatus: [],
		receiptTypeId: null,//入库类型
		receiptType: [],
		purchaseOrderId: null, //采购订单
		purchaseOrder: [],
		arrivalId: null,//到货单
		arrival: [],
		returnId: null,//销售退货单
		return: [],
		requester: null,//申请人
		requestDate: null,//申请日期
		totalQuantity: null,//入库总量
		approver: null,//审批人
		receiptDate: null,//入库日期
		receiptPhoto: null,//入库照片
		files: [],
		remark: null,//备注
		warehouseId: null,//仓库
		warehouse: [],
		approvalTime: null,//审批时间
		tableData: []
	});
	//验证
	const rules = reactive({
		receiptNumber: [],//入库单号
		entryStatus: [{ required: true, message: '不能为空', trigger: 'blur' }],//入库状态
		receiptType: [{ required: true, message: '不能为空', trigger: 'blur' }],//入库类型
		arrival: [],//到货单
		return: [],//销售退货单
		requester: [{ required: true, message: '不能为空', trigger: 'blur' }],//申请人
		requestDate: [{ required: true, message: '不能为空', trigger: 'blur' }],//申请日期
		totalQuantity: [{ required: true, message: '不能为空', trigger: 'blur' }],//入库总量
		approver: [{ required: true, message: '不能为空', trigger: 'blur' }],//审批人
		receiptDate: [{ required: true, message: '不能为空', trigger: 'blur' }],//入库日期
		receiptPhoto: [],//入库照片
		remark: [],//备注
		warehouse: [],//仓库
		approvalTime: [],//审批时间
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//入库状态
	const entryStatusTags = ref([]);
	const entryStatusIndex = ref(-1);
	//入库类型
	const receiptTypeOption = ref([]);
	const receiptTypeIndex = ref(-1);
	const receiptType = ref(null);
	//到货单
	const arrivalOption = ref([]);
	const arrivalIndex = ref(-1);
	const arrival = ref(null);
	//采购订单
	const purchaseOrderOption = ref([]);
	const purchaseOrderIndex = ref(-1);
	const purchaseOrder = ref(null);
	//销售退货单
	const returnOption = ref([]);
	const returnIndex = ref(-1);
	const returns = ref(null);
	//仓库
	const warehouseOption = ref([]);
	const warehouseIndex = ref(-1);
	const warehouse = ref(null);
	const dialogVisible = ref(false);
	//入库产品
	const productOption = ref([]);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getEntryStatus();
				getReceiptType();
				getOrderAll();
				getReturn();
				if (!route.query.id) {
					entryStatusIndex.value = 0;
					formData.value.entryStatusId = 156;
				}
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.requester = decodedToken?.username;
			formData.value.approver = decodedToken?.username;
			//
			return true;
		}
		//
		const result = await request({
			url: '/demand/selectWarehouseReceiptById',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		formData.value.tableData = [...result.data.t.inboundDetailList];
		return true;
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		// if (type === 'entryStatusId') {
		// 	if (entryStatusIndex.value === index) {
		// 		formData.value[type] = null;
		// 		entryStatusIndex.value = -1;
		// 		return;
		// 	}
		// 	entryStatusIndex.value = index;
		// 	formData.value[type] = entryStatusTags.value[index].value;
		// }
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'receiptType', //哪一个下拉框，根据ref
			option: receiptTypeOption, //下拉列表选项
			indexVar: receiptTypeIndex, //当前选中项
			idVar: 'receiptTypeId', //当前id值
			blurRef: receiptType, //ref
		}, {
			type: 'purchaseOrder', //哪一个下拉框，根据ref
			option: purchaseOrderOption, //下拉列表选项
			indexVar: purchaseOrderIndex, //当前选中项
			idVar: 'purchaseOrderId', //当前id值
			blurRef: purchaseOrder, //ref
			fun: getDetailById
		}, {
			type: 'returns', //哪一个下拉框，根据ref
			option: returnOption, //下拉列表选项
			indexVar: returnIndex, //当前选中项
			idVar: 'returnId', //当前id值
			blurRef: returns, //ref
			fun: getReturnDetailProduct
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
		//
		// if (type === 'returns') {
		// 	const index = findIndexByLabel(returnOption.value, value[0], 'value');
		// 	//
		// 	returnOption.value[index].orderDetail.forEach((item : any, key : number) => {
		// 		getProductById(item.productId);
		// 	});
		// }
	}

	//设置一个
	const setTableData = () => {
		formData.value.tableData.push({
			id: +new Date(),
			productId: null,//入库产品
			unitId: null, //单位
			inboundQuantity: null,//入库数量
			notes: null,//备注
			purchaseOrderId: null,//采购订单
			returnId: null,//销售退货订单
		});
	}
	//复制一个
	const copyTableData = (index : number) => {
		//...
		const item = { ...formData.value.tableData[index] };
		item.id = +new Date();
		formData.value.tableData.push(item);
		//
	}
	//删除一个
	const deleteTableData = (index : number) => {
		formData.value.tableData.splice(index, 1);
	}
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	const tableCellClick = (row : any, column : any, cell : HTMLTableCellElement, event : Event) => {
		if (route.query.id) {
			return;
		}
		types.value = '';
		//入库产品
		if (column.property === 'productId') {
			types.value = 'select-icon';
			selectCell.value.option = [...productOption.value];
		}
		//入库数量
		if (column.property === 'inboundQuantity') {
			types.value = 'number';
		}
		//备注
		if (column.property === 'notes') {
			types.value = 'text';
		}
		element.value = cell;
		//
		selectCell.value.id = row.id;
		selectCell.value.property = column.property;
		//
		levitationParams.value = row[column.property];

		setTimeout(() => {
			levitationRef.value.getElementInfo();
		}, 1);
		//
	}
	//获取入库状态
	const getEntryStatus = async () => {
		const data = await getShipments('entry_status', 'tag');
		entryStatusTags.value = [];
		data.forEach((item : any, key : number) => {
			entryStatusTags.value.push(item);
			if (formData.value.entryStatusId === item.value) {
				entryStatusIndex.value = key;
			}
		});
	}
	//获取入库类型
	const getReceiptType = async () => {
		const data = await getShipments('receipt_type');
		receiptTypeOption.value = [];
		data.forEach((item : any, key : number) => {
			receiptTypeOption.value.push(item);
			if (formData.value.receiptTypeId === item.value) {
				formData.value.receiptType = [item.value];
				receiptTypeIndex.value = key;
			}
		});
	}
	//获取所有采购订单
	const getOrderAll = async () => {
		const result = await request({
			url: '/demand/selectOrderAll',
			params: {
				//待入库
				id: 150
			},
		});
		//
		console.log('getOrderAll --->', result);
		//
		purchaseOrderOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			purchaseOrderOption.value.push({
				label: `${item.purchaseOrderNumber}_${item.totalAmount}_${item.supplier.supplierShortName}`,
				value: item.purchaseOrderId,
				icon: Van,
				color: '#faa30c'
			});
			//
			if (formData.value?.purchaseOrderId === item.purchaseOrderId) {
				formData.value.purchaseOrder = [item.purchaseOrderId];
				purchaseOrderIndex.value = key;
				//
			}
		});
	}
	//获取退货单
	const getReturn = async () => {
		const result = await request({
			url: '/login/selectSalesReturnAll',
			params: {
				returnStatusId: 133
			},
		});
		//
		console.log('getReturn --->', result);
		//
		returnOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			returnOption.value.push({
				label: `${item.salesOrder.orderNumber} ${formatDate(item.returnApplicationDate)}退货_${item.customer.customerName}`,
				value: item.returnId,
				icon: Grid,
				color: '#5283ff',
				orderDetail: item.salesOrder.orderDetail,
			});
			//
			if (formData.value?.returnId === item.returnId) {
				formData.value.return = [item.returnId];
				returnIndex.value = key;
				//
			}
		});
	}
	//根据id获取商品信息
	const getProductById = async (id : number, key ?: number) => {
		const result = await request({
			url: '/demand/selectProductByPId',
			params: {
				id
			}
		});
		console.log('formData.value.tableData --->', formData.value.tableData);
		formData.value.tableData.forEach((item : any, key : number) => {
			if (item.productId === result.data.t.productId) {
				item.unitId = result.data.t.unitId;
				item.inboundQuantity = productOption.value[key].purchaseQuantity; //
				item.purchaseOrderId = productOption.value[key].purchaseOrderId;
				item.returnId = productOption.value[key].returnId;
				item.products = {
					label: `${result.data.t?.productName}${result.data.t?.model} | 在库${result.data.t?.currentInventory}件`,
					value: result.data.t?.productId,
					icon: GoodsFilled,
					color: '#5283ff'
				}
			}
		});
		//
		computeAll();
	}
	//根据采购订单id
	const getDetailById = async (id : number | string) => {
		const result = await request({
			url: '/demand/selectOrderById',
			params: {
				id
			}
		});
		//
		console.log('getDetailById --->', result);
		const { order, purchaseDetailList } = result.data.t;
		productOption.value = [];
		purchaseDetailList.forEach((item : any, key : number) => {
			//到货产品
			productOption.value.push({
				label: `${item.product.productName}${item.product.model} | 在库${item.product.currentInventory}件`,
				value: item.product.productId,
				icon: UploadFilled,
				color: '#5283ff',
				purchaseOrderId: item.purchaseOrderId,
				purchaseQuantity: item.purchaseQuantity
			});
		});
	}
	//
	const getReturnDetailProduct =async (id : number | string) => {
		const result = await request({
			url: '/login/selectReturnDetailProduct',
			params: {
				id
			}
		});
		//
		console.log('getReturnDetailProduct --->', result);
		productOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			productOption.value.push({
				label: `${item.product.productName}${item.product.model} | 在库${item.product.currentInventory}件`,
				value: item.product.productId,
				icon: UploadFilled,
				color: '#5283ff',
				purchaseQuantity: item.returnQuantity,
				returnId: item.returnOrderId,
			});
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let type = '';
				if (!route.query.id) {
					type = '/addWarehouseReceipt';
				} else {
					type = '/updateWarehouseReceiptById';
				}
				const data = { ...formData.value, inboundDetailList: [...formData.value.tableData] };
				delete data.entryStatus;
				delete data.receiptType;
				delete data.arrival;
				delete data.return;
				delete data.warehouse;
				delete data.tableData;
				//
				const result = await request({
					url: '/demand' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
					if (!route.query.id) {
						router.push({ query: { id: result.data.t } });
						route.query.id = result.data.t;
						//修改采购订单、采购到货单状态
						console.log('data.inboundDetailList --->', data.inboundDetailList);
						data.inboundDetailList.forEach((item : any, key : number) => {
							//如果是入库类型是：采购入库
							if(formData.value.receiptTypeId===178){
								request({
									url: '/demand/selectOrderById',
									params: {
										id: item.purchaseOrderId
									},
								}).then((result1) => {
									const item1 = result1.data.t.order;
									if (item1.procurementStatusId === 150) {
										item1.procurementStatusId = 152;
										//根据采购订单id更新采购订单状态
										request({
											url: '/demand/updateOrderByStatusId',
											method: 'post',
											data: item1,
										}).then((results : any) => {
											console.log('updateOrderByStatusId --->', results);
										});
										//根据采购订单id更新到货单状态
										item1.entryStatusId = 158;
										request({
											url: '/demand/updatePurchaseArrivalByOId',
											method: 'post',
											data: item1,
										}).then((results : any) => {
											console.log('updatePurchaseArrivalByOId --->', results);
										});
									}
								});
							}
							//如果是入库类型是：退货入库
							if(formData.value.receiptTypeId===179){
								request({
									url: '/login/selectSalesReturnById',
									params: {
										id: item.returnId
									},
								}).then((result1) => {
									const item1 = result1.data.t;
									if (item1.returnStatusId === 133) {
										item1.returnStatusId = 134;
										//根据退货订单id更新订单状态
										request({
											url: '/login/updateSalesReturn',
											method: 'post',
											data: item1,
										}).then((results : any) => {
											console.log('updateSalesReturn --->', results);
										});
									}
								});
							}
						});
					}
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//失去焦点 ***** 重要！重要！重要！
	const levitationBlur = () => {
		element.value = null;
	}
	//内容改变
	const levitationChange = (value : string | number) => {
		// console.log('value --->', value);
		formData.value.tableData.forEach((item : any, key : number) => {
			// console.log('item.id --->', item.id, 'selectCell.value.id --->', selectCell.value.id);
			if (item.id === selectCell.value.id) {
				item[selectCell.value.property] = value;
				if (selectCell.value.property === 'productId') {
					getProductById(value, key);
				}
				if (selectCell.value.property === 'inboundQuantity') {
					computeAll();
				}
			}
		});
	}
	//滚动
	const handleScroll = (e : any) => {
		// console.log('handleScroll --->', e);
		if (element.value === null) return;
		levitationRef.value.getElementInfo();
	}
	//
	const computeAll = () => {
		formData.value.totalQuantity = 0;
		formData.value.tableData.forEach((item : any, key : number) => {
			//入库总量
			formData.value.totalQuantity += Number(item.inboundQuantity);
		});
	}
	//图片上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.receiptPhoto = res.t;
	}
	//暴露属性和方法给外部使用
	defineExpose({
		openDialog
	})
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.el-scrollbar__view {
		display: block !important;
	}

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.el-upload-list--text {
		display: none;
	}
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>